/**
 * @tag controllers, home
 * Displays a table of report_descriptors.  Lets the user 
 * ["ReportDescriptorController.prototype.form submit" create], 
 * ["ReportDescriptorController.prototype.&#46;edit click" edit],
 * or ["ReportDescriptorController.prototype.&#46;destroy click" destroy] report_descriptors.
 */
jQuery.Controller.extend('Bugstat.Controllers.ReportDescriptorController',
/* @Static */
{
    onDocument: false
},
/* @Prototype */
{
	report_descriptor: '',
	
	/**
     * Init report descriptor
     */
    initController: function(report_descriptor)
	{
		this.report_descriptor = report_descriptor;

		// Add descriptor tag
        this.retrieveDescriptorTag().html( '//bugstat/views/report_descriptor/show.ejs', report_descriptor);

		this.updateToggleText()
		
		// Show report in case this report is with forced visiblility
		if ( report_descriptor.visible )
		{
			report_descriptor.visible = 0;
			this.showReport()
		}
    },

    /**
     * Load report graph and display it to the user
     * @param {jQuery} el The report_descriptor's edit link element.
     */
	showReport: function() {
		var report_name = 'report_' + this.report_descriptor.id;
		
		// Add report tag if it is not yet there
		if(!$('.' + report_name).length) 
		{			
			$("#report_graphs").append( '//bugstat/views/report/init.ejs', this.report_descriptor);			
		}
            
		var report_controller = this.retrieveReportTag();
		report_controller.bugstat_report();
		report_controller.bugstat_report("initController", this.report_descriptor );
		report_controller.bugstat_report( "showReport" );				
	},
	
	hideReport: function() {
		var report_controller = this.retrieveReportTag();
		
		report_controller.bugstat_report();
		report_controller.bugstat_report( "hideReport" );
	},
	
	retrieveReportTag : function() {
		return $('.report_' + this.report_descriptor.id);
	},
	
	retrieveDescriptorTag: function() {
		return $(".report_descriptor_"+ this.report_descriptor.identity() );
	},
	
	updateToggleText: function() {
		var text = Bugstat.Controllers.ReportController.isShowing( this.report_descriptor.id ) ? "Hide" : "Show";
		$('.bugstat_models_report_descriptor_' + this.report_descriptor.id + ' .toggleReport').html( text );
	},

    '.toggleReport mousedown': function(el) {	
        var report_descriptor = el.parents().model();
		var report_id	      = this.report_descriptor.id;

		if ( Bugstat.Controllers.ReportController.isShowing( report_id ) ) {
			this.hideReport( report_id );
		}
		else {
			this.showReport( report_id );
		}
    },

	'reportShown subscribe' : function(called, report) {
		if ( report.id == this.report_descriptor.id ) 
		{
			this.updateToggleText();			 		
			this.retrieveDescriptorTag().addClass('open-report-item');		
		}
	},
	
	'reportHidden subscribe' : function(called, report){
		
		if ( report.id == this.report_descriptor.id ) 
		{
			this.updateToggleText();
			this.retrieveDescriptorTag().removeClass('open-report-item');
		}
	}
});